package com.storage.configuration;

import com.storage.StorageTemplate;
import com.storage.client.AliyunOssStorageClient;
import com.storage.client.LocalStorageClient;
import com.storage.client.StorageClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Configuration
@ConditionalOnMissingBean(StorageClient.class)
public class StorageAutoConfiguration {

    @Autowired
    private StorageConfiguration configuration;

    /**
     * 本地存储
     * @return
     */
    @Bean
    public List<LocalStorageClient> localStorageClient() {
        return configuration.getLocal().stream().filter(local -> local.getEnable()).map(local -> {
            LocalStorageClient localStorageClient = new LocalStorageClient();
            localStorageClient.setClient(local.getClient());
            return localStorageClient;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

    /**
     * 本地存储
     * @return
     */
    @Bean
    @ConditionalOnClass(name = "com.aliyun.oss.OSS")
    public List<AliyunOssStorageClient> aliyunOssStorageClient() {
        return configuration.getAliyunOss().stream().filter(aliyunOss -> aliyunOss.getEnable()).map(aliyunOss -> {
            AliyunOssStorageClient aliyunOssStorageClient = new AliyunOssStorageClient();
            aliyunOssStorageClient.setClient(aliyunOss.getClient());
            aliyunOssStorageClient.setAliyunOss(aliyunOss);
            return aliyunOssStorageClient;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

    /**
     * 文件存储服务
     */
    @Bean
    public StorageTemplate getStorageTemplate(
                                              List<List<? extends StorageClient>> storageClientList
                                              ) {
        StorageTemplate storageTemplate=new StorageTemplate();
        storageTemplate.setConfiguration(configuration);
        storageTemplate.setStorageClientList(storageClientList);
        return storageTemplate;
    }

}
